<template>
  <div>
    <el-cascader @change="categoryChange" :options="categoryTree" :props="defaultProps"
                 v-model="categoryIdArrayLocal"
                 placeholder="点击搜索"
                 filterable
                 ref="cascaderRef"
                 :show-all-levels="showAllLevelsLocal"></el-cascader>
  </div>
</template>

<script>
import categoryApi from '../../../api/categoryApi'

export default {
  name: 'categoryTreeCascader',
  props: ['categoryIdArray', 'showAllLevels', 'categoryId'],
  data () {
    return {
      categoryTree: [],
      defaultProps: {
        label: 'name',
        children: 'children',
        value: 'catId',  // 必须指定value，之后会被作为id，否则报错
        expandTrigger: 'hover'
      },
      categoryIdArrayLocal: [],
      showAllLevelsLocal: false,
    }
  },
  methods: {
    categoryChange (threeLevelCatId) {
      //console.log(this.$refs.cascaderRef.getCheckedNodes())
      this.$emit('category-change', threeLevelCatId)
      this.$emit('category-lowest-level-change', threeLevelCatId[threeLevelCatId.length - 1])

    },
    getProductCategory () {
      categoryApi.getCategoryTree().then(({data}) => {
        this.categoryTree = data.treeCategoryList.children
      })
    },
    async findCategoryIdPath (categoryId) {
      let p = await categoryApi.findCategoryIdPath(categoryId)
      this.categoryIdArrayLocal = p.data.filter(d => {
        return d != 0
      }).reverse()
    }
  },
  created () {
    this.getProductCategory()
  },
  watch: {
    categoryIdArray (val) {
      this.categoryIdArrayLocal = val
    },
    showAllLevels (val) {
      console.log('子组件接收到showAllLevels = ', val)
      if (val) {
        this.showAllLevelsLocal = val
      }
    },
    categoryId (val) {
      if (val) {
        this.findCategoryIdPath(val)
      }
    }
  }
}
</script>

<style scoped>

</style>
